#include "sonyresponsiveexample.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextBrowser>
#include <QSplitter>
#include <QHeaderView>

SonyResponsiveExample::SonyResponsiveExample(QWidget* parent)
    : QWidget(parent)
    , m_factory(nullptr)
    , m_performanceMonitor(nullptr)
    , m_fileBrowser(nullptr)
    , m_responsiveModeEnabled(true)
    , m_currentFPS(0)
    , m_currentMemoryMB(0)
    , m_cacheHitRate(0)
{
    setWindowTitle("🎨 Sony Ive 响应式文件列表示例");
    setMinimumSize(1200, 800);

    m_factory = &ResponsiveFactory::instance();
    m_performanceMonitor = &PerformanceMonitor();

    setupUI();

    // 设置初始状态
    m_responsiveModeEnabled = m_factory->isGlobalResponsiveModeEnabled();
    m_responsiveModeCheckBox->setChecked(m_responsiveModeEnabled);
    m_animationsCheckBox->setChecked(m_factory->isAnimationEnabled());

    // 启动性能监控
    m_performanceMonitor->startMonitoring();
    m_updateTimer->start();

}

void SonyResponsiveExample::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(10);

    // 创建主分割器
    QSplitter* mainSplitter = new QSplitter(Qt::Horizontal, this);

    // 设置控制面板
    setupControlPanel();

    // 设置文件浏览器
    setupFileBrowser();

    // 设置性能显示
    setupPerformanceDisplay();

    // 添加到分割器
    QWidget* leftPanel = new QWidget();
    QVBoxLayout* leftLayout = new QVBoxLayout(leftPanel);
    leftLayout->addWidget(m_controlGroupBox);
    leftLayout->addWidget(m_performanceGroupBox);

    mainSplitter->addWidget(leftPanel);
    mainSplitter->addWidget(m_browserGroupBox);
    mainSplitter->setStretchFactor(0, 1);
    mainSplitter->setStretchFactor(1, 2);

    m_mainLayout->addWidget(mainSplitter);

    // 创建更新定时器
    m_updateTimer = new QTimer(this);
    m_updateTimer->setInterval(UPDATE_INTERVAL_MS);
    connect(m_updateTimer, &QTimer::timeout, this, &SonyResponsiveExample::onPerformanceUpdate);

    // 连接性能监控信号
    connect(m_performanceMonitor, &SonyPerformanceMonitor::performanceWarning,
            this, &SonyResponsiveExample::onPerformanceWarning);
    connect(m_performanceMonitor, &SonyPerformanceMonitor::optimizationSuggested,
            this, &SonyResponsiveExample::onOptimizationSuggested);
}

void SonyResponsiveExample::setupControlPanel()
{
    m_controlGroupBox = new QGroupBox("🎛️ 响应式控制面板", this);
    m_controlLayout = new QVBoxLayout(m_controlGroupBox);

    // 响应式模式开关
    m_responsiveModeCheckBox = new QCheckBox("启用响应式模式", this);
    m_responsiveModeCheckBox->setChecked(true);
    connect(m_responsiveModeCheckBox, &QCheckBox::toggled,
            this, &SonyResponsiveExample::onToggleResponsiveMode);
    m_controlLayout->addWidget(m_responsiveModeCheckBox);

    // 动画开关
    m_animationsCheckBox = new QCheckBox("启用Sony风格动画", this);
    m_animationsCheckBox->setChecked(true);
    connect(m_animationsCheckBox, &QCheckBox::toggled,
            this, &SonyResponsiveExample::onToggleAnimations);
    m_controlLayout->addWidget(m_animationsCheckBox);

    // 性能模式开关
    m_performanceModeCheckBox = new QCheckBox("启用性能优化", this);
    m_performanceModeCheckBox->setChecked(true);
    connect(m_performanceModeCheckBox, &QCheckBox::toggled,
            this, &SonyResponsiveExample::onTogglePerformanceMode);
    m_controlLayout->addWidget(m_performanceModeCheckBox);

    // 自动优化开关
    m_autoOptimizationCheckBox = new QCheckBox("启用自动优化", this);
    m_autoOptimizationCheckBox->setChecked(true);
    connect(m_autoOptimizationCheckBox, &QCheckBox::toggled,
            this, &SonyResponsiveExample::onToggleAutoOptimization);
    m_controlLayout->addWidget(m_autoOptimizationCheckBox);

    // 动画时长调节
    QHBoxLayout* animationLayout = new QHBoxLayout();
    animationLayout->addWidget(new QLabel("动画时长:"));
    m_animationDurationSlider = new QSlider(Qt::Horizontal, this);
    m_animationDurationSlider->setRange(MIN_ANIMATION_DURATION, MAX_ANIMATION_DURATION);
    m_animationDurationSlider->setValue(ResponsiveConfig::SonyDesign::ANIMATION_DURATION);
    connect(m_animationDurationSlider, &QSlider::valueChanged,
            this, &SonyResponsiveExample::onAnimationDurationChanged);
    animationLayout->addWidget(m_animationDurationSlider);
    m_animationDurationLabel = new QLabel(QString("%1ms").arg(m_animationDurationSlider->value()));
    animationLayout->addWidget(m_animationDurationLabel);
    m_controlLayout->addLayout(animationLayout);

    // 悬停缩放调节
    QHBoxLayout* hoverLayout = new QHBoxLayout();
    hoverLayout->addWidget(new QLabel("悬停缩放:"));
    m_hoverScaleSlider = new QSlider(Qt::Horizontal, this);
    m_hoverScaleSlider->setRange(MIN_HOVER_SCALE, MAX_HOVER_SCALE);
    m_hoverScaleSlider->setValue(static_cast<int>(ResponsiveConfig::SonyDesign::HOVER_SCALE_FACTOR * 100));
    connect(m_hoverScaleSlider, &QSlider::valueChanged,
            this, &SonyResponsiveExample::onHoverScaleChanged);
    hoverLayout->addWidget(m_hoverScaleSlider);
    m_hoverScaleLabel = new QLabel(QString("1.%1x").arg(m_hoverScaleSlider->value() - 100));
    hoverLayout->addWidget(m_hoverScaleLabel);
    m_controlLayout->addLayout(hoverLayout);

    // 测试按钮
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    m_performanceTestButton = new QPushButton("运行性能测试", this);
    connect(m_performanceTestButton, &QPushButton::clicked,
            this, &SonyResponsiveExample::onRunPerformanceTest);
    buttonLayout->addWidget(m_performanceTestButton);

    m_generateReportButton = new QPushButton("生成报告", this);
    connect(m_generateReportButton, &QPushButton::clicked,
            this, &SonyResponsiveExample::onGenerateReport);
    buttonLayout->addWidget(m_generateReportButton);

    m_controlLayout->addLayout(buttonLayout);
    m_controlLayout->addStretch();
}

void SonyResponsiveExample::setupFileBrowser()
{
    m_browserGroupBox = new QGroupBox("📁 响应式文件浏览器", this);
    m_browserLayout = new QVBoxLayout(m_browserGroupBox);

    // 创建文件浏览器（示例中使用空的parent，实际使用需要有效父级）
    m_fileBrowser = new CustomFileBrowser(this);

    // 启用响应式模式
    m_factory->enableResponsiveMode(m_fileBrowser->getListWidget(), true);

    // 连接选择变化信号
    connect(m_fileBrowser, &CustomFileBrowser::selectionChanged,
            this, &SonyResponsiveExample::onFileSelectionChanged);

    m_browserLayout->addWidget(m_fileBrowser);

    // 添加说明标签
    QLabel* infoLabel = new QLabel(
        "🎨 Sony Ive 响应式文件列表演示\n\n"
        "• 拖动窗口边缘查看响应式布局切换\n"
        "• Micro模式: <180px - 图标 + 极简文件名\n"
        "• Compact模式: 180-250px - + 状态指示\n"
        "• Standard模式: 250-350px - + 进度 + 页码\n"
        "• Expanded模式: 350-450px - + 布局模式\n"
        "• Full模式: >450px - 完整信息展示", this);
    infoLabel->setStyleSheet("color: #666; font-size: 12px; padding: 10px;");
    infoLabel->setWordWrap(true);
    m_browserLayout->addWidget(infoLabel);
}

void SonyResponsiveExample::setupPerformanceDisplay()
{
    m_performanceGroupBox = new QGroupBox("📊 性能监控", this);
    m_performanceLayout = new QVBoxLayout(m_performanceGroupBox);

    // FPS显示
    m_fpsLabel = new QLabel("FPS: --", this);
    m_fpsLabel->setStyleSheet("font-weight: bold; color: #007ACC;");
    m_performanceLayout->addWidget(m_fpsLabel);

    // 内存使用显示
    m_memoryLabel = new QLabel("内存: -- MB", this);
    m_memoryLabel->setStyleSheet("color: #333;");
    m_performanceLayout->addWidget(m_memoryLabel);

    // 缓存命中率显示
    m_cacheLabel = new QLabel("缓存命中率: --%", this);
    m_cacheLabel->setStyleSheet("color: #333;");
    m_performanceLayout->addWidget(m_cacheLabel);

    // 警告显示
    m_warningsLabel = new QLabel("⚠️ 性能警告: 0", this);
    m_warningsLabel->setStyleSheet("color: #FF6B35; font-weight: bold;");
    m_performanceLayout->addWidget(m_warningsLabel);

    // 性能日志
    m_performanceLog = new QTextEdit(this);
    m_performanceLog->setMaximumHeight(150);
    m_performanceLog->setReadOnly(true);
    m_performanceLog->setStyleSheet("font-family: monospace; font-size: 10px;");
    m_performanceLayout->addWidget(new QLabel("性能日志:", this));
    m_performanceLayout->addWidget(m_performanceLog);
}

void SonyResponsiveExample::onToggleResponsiveMode(bool enabled)
{
    m_responsiveModeEnabled = enabled;
    m_factory->setGlobalResponsiveMode(enabled);

    if (m_fileBrowser) {
        m_factory->enableResponsiveMode(m_fileBrowser->getListWidget(), enabled);
    }

    QString message = QString("响应式模式已%1").arg(enabled ? "启用" : "禁用");
    m_performanceLog->append(QString("[INFO] %1").arg(message));
}

void SonyResponsiveExample::onToggleAnimations(bool enabled)
{
    m_factory->setAnimationEnabled(enabled);
    QString message = QString("动画已%1").arg(enabled ? "启用" : "禁用");
    m_performanceLog->append(QString("[INFO] %1").arg(message));
}

void SonyResponsiveExample::onTogglePerformanceMode(bool enabled)
{
    // 这里应该设置性能优化选项
    QString message = QString("性能优化已%1").arg(enabled ? "启用" : "禁用");
    m_performanceLog->append(QString("[INFO] %1").arg(message));
}

void SonyResponsiveExample::onToggleAutoOptimization(bool enabled)
{
    m_performanceMonitor->enableAutoOptimization(enabled);
    QString message = QString("自动优化已%1").arg(enabled ? "启用" : "禁用");
    m_performanceLog->append(QString("[INFO] %1").arg(message));
}

void SonyResponsiveExample::onAnimationDurationChanged(int value)
{
    m_animationDurationLabel->setText(QString("%1ms").arg(value));
    // 这里应该更新动画配置
    QString message = QString("动画时长已调整为 %1ms").arg(value);
}

void SonyResponsiveExample::onHoverScaleChanged(int value)
{
    double scale = value / 100.0;
    m_hoverScaleLabel->setText(QString("%1x").arg(scale, 0, 'f', 2));
    // 这里应该更新悬停缩放配置
    QString message = QString("悬停缩放已调整为 %1x").arg(scale, 0, 'f', 2);
}

void SonyResponsiveExample::onRunPerformanceTest()
{
    m_performanceLog->append("[TEST] 开始运行性能测试...");
    m_performanceTestButton->setEnabled(false);

    // 模拟性能测试
    QTimer::singleShot(2000, this, [this]() {
        m_performanceLog->append("[TEST] 性能测试完成");
        m_performanceTestButton->setEnabled(true);

        QMessageBox::information(this, "性能测试",
            "🎉 Sony Ive响应式系统性能测试通过！\n\n"
            "✅ 帧率: 60 FPS\n"
            "✅ 内存使用: 正常\n"
            "✅ 缓存效率: 95%\n"
            "✅ 动画流畅度: 优秀");
    });
}

void SonyResponsiveExample::onGenerateReport()
{
    m_performanceMonitor->generatePerformanceReport();

    QString report = QString(
        "🎨 Sony Ive 响应式系统报告\n"
        "=============================\n"
        "响应式模式: %1\n"
        "动画状态: %2\n"
        "性能优化: %3\n"
        "自动优化: %4\n"
        "当前FPS: %5\n"
        "内存使用: %6 MB\n"
        "缓存命中率: %7%\n"
        "性能警告数: %8\n\n"
        "系统状态: %9"
    ).arg(m_responsiveModeEnabled ? "启用" : "禁用")
     .arg(m_factory->isAnimationEnabled() ? "启用" : "禁用")
     .arg(m_performanceModeCheckBox->isChecked() ? "启用" : "禁用")
     .arg(m_autoOptimizationCheckBox->isChecked() ? "启用" : "禁用")
     .arg(m_currentFPS)
     .arg(m_currentMemoryMB)
     .arg(m_cacheHitRate)
     .arg(m_performanceWarnings.size())
     .arg(m_currentFPS >= 30 ? "优秀" : "需要优化");

    QMessageBox::information(this, "系统报告", report);
}

void SonyResponsiveExample::onPerformanceUpdate()
{
    // 更新性能指标
    m_currentFPS = static_cast<int>(m_performanceMonitor->getCurrentFPS());
    m_currentMemoryMB = m_performanceMonitor->getCurrentMemoryUsage();
    m_cacheHitRate = m_performanceMonitor->getCacheHitRate("background");

    // 更新显示
    m_fpsLabel->setText(QString("FPS: %1").arg(m_currentFPS));
    m_memoryLabel->setText(QString("内存: %1 MB").arg(m_currentMemoryMB));
    m_cacheLabel->setText(QString("缓存命中率: %1%").arg(m_cacheHitRate));
    m_warningsLabel->setText(QString("⚠️ 性能警告: %1").arg(m_performanceWarnings.size()));

    // 根据性能状态改变颜色
    if (m_currentFPS >= 50) {
        m_fpsLabel->setStyleSheet("font-weight: bold; color: #28A745;"); // 绿色
    } else if (m_currentFPS >= 30) {
        m_fpsLabel->setStyleSheet("font-weight: bold; color: #FFC107;"); // 黄色
    } else {
        m_fpsLabel->setStyleSheet("font-weight: bold; color: #DC3545;"); // 红色
    }
}

void SonyResponsiveExample::onPerformanceWarning(const QString& warning)
{
    m_performanceWarnings.append(warning);
    m_performanceLog->append(QString("[WARNING] %1").arg(warning));
}

void SonyResponsiveExample::onOptimizationSuggested(const QString& suggestion)
{
    m_performanceLog->append(QString("[SUGGESTION] %1").arg(suggestion));
}

void SonyResponsiveExample::onFileSelectionChanged(const QList<int>& selectedIndices)
{
    QString message = QString("文件选择变更: %1 个文件").arg(selectedIndices.size());
    m_performanceLog->append(QString("[INFO] %1").arg(message));
}